package com.dirk.happie.activities;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.dirk.happie.R;
import com.dirk.happie.adapters.BasketListAdapter;
import com.dirk.happie.beans.ArticleBean;
import com.dirk.happie.beans.BasketItem;
import com.dirk.happie.beans.ExtraBean;
import com.dirk.happie.beans.OptionsBean;
import com.dirk.happie.network.GetArticlesTask;
import com.dirk.happie.network.RequestCompleteListener;
import com.dirk.happie.utils.App;
import com.dirk.happie.utils.Availablity;
import com.dirk.happie.utils.Common;
import com.dirk.happie.utils.Keys;
import com.dirk.happie.utils.LogoDownloader;

public class BasketActivity extends Activity {
	private GetArticlesTask getArticlesTask = null;
	private App mApp;
	// ArrayList<BasketItem> product_data;
	List<ArticleBean> articles;
	private String articleId;
	private String categoryId;
	// private String companyId;
	private String optionId;
	String[] extraIDs;

	private LogoDownloader logoDownloader = null;
	private String cacheFolderPath = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_basket);
		this.mApp = ((App) getApplication());
		// product_data = mApp.getBasketList();
		ImageView companyLogoView = (ImageView) findViewById(R.id.img_company);
		cacheFolderPath = Environment.getExternalStorageDirectory().getPath() + "/happie_cache";
		File file = new File(cacheFolderPath);
		file.mkdirs();
		logoDownloader = new LogoDownloader();
		if (mApp.getCompanyLogo() != null) {
			logoDownloader.download(Keys.LOGOS_URL + mApp.getCompanyLogo(), cacheFolderPath + "/" + Common.getMD5(mApp.getCompanyLogo()), companyLogoView);
		}
		// companyId = getIntent().getStringExtra(Keys.KEY_COMPANY_ID);
		articleId = getIntent().getStringExtra(Keys.KEY_ARTICLE_ID);
		categoryId = getIntent().getStringExtra(Keys.KEY_CATEGORY_ID);
		optionId = getIntent().getStringExtra(Keys.KEY_OPTION_ID);
		extraIDs = getIntent().getStringArrayExtra(Keys.KEY_EXTRA_CHECK);

		parseBasketJson();

		footerMenuListeners();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		createListView();
	}

	private void createListView() {
		ListView lv = (ListView) findViewById(R.id.listProducts);
		BasketListAdapter adapter = new BasketListAdapter(this, R.layout.basket_list_item, mApp.getBasketList());
		lv.setFastScrollEnabled(true);
		lv.setScrollingCacheEnabled(false);
		lv.setAdapter(adapter);

		buttonListeners();
	}

	private void parseBasketJson() {
		getArticlesTask = new GetArticlesTask(this);
		getArticlesTask.setRequestCompleteListener(new RequestCompleteListener<List<ArticleBean>>() {

			@Override
			public void onSuccess(List<ArticleBean> result) {

				articles = result;

				addToBasket();

				createListView();
			}

			@Override
			public void onFailure(final String message) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
					}
				});
			}
		});
		if (Availablity.isNetworkAvailable(this)) {
			if (categoryId != null) {
				getArticlesTask.execute(categoryId);
			} else {
				createListView();
			}

		} else {
			createListView();
			Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
		}

	}

	private void addToBasket() {
		boolean isOption = false;
		String idOption = "";
		if (articles != null && articleId != null) {
			for (int i = 0; i < articles.size(); i++) {
				ArticleBean curArticle = articles.get(i);
				if (curArticle.getArticleId().equals(articleId)) {

					if (optionId != null && curArticle.getOption() != null && curArticle.getOption().size() > 0) {
						for (OptionsBean option : curArticle.getOption()) {
							if (option.getIdOption().equals(optionId)) {
								ArticleBean bean = new ArticleBean(curArticle);
								bean.setArticleDescription(option.getOptionDescription());
								bean.setArticlePrice(option.getOptionPrice());
								bean.setArticleId(option.getIdArticle());
								bean.setOptionId(option.getIdOption());
								bean.setArticleSize(option.getOptionSize());
								bean.setType("0");
								idOption = option.getIdOption();

								addArticleIfExists(bean);
								// mApp.basketList.add(new BasketItem(bean));
								isOption = true;
							}
						}
					} else {
						if (Common.compareOfferDate(curArticle)) {
							curArticle.setArticlePrice(curArticle.getOfferPrice());
						}
						curArticle.setType("1");
						curArticle.setOptionId(idOption);
						addArticleIfExists(curArticle);
						// mApp.basketList.add(new BasketItem(curArticle));
					}

					if (curArticle.getExtra() != null && curArticle.getExtra().size() > 0 && extraIDs != null) {

						for (final ExtraBean extra : curArticle.getExtra()) {

							for (int j = 0; j < extraIDs.length; j++) {
								if (extraIDs[j].equals(extra.getIdExtra())) {
									if (isOption) {
										extra.setType("0");
										extra.setIdOption(idOption);
									} else {
										extra.setType("1");
									}
									addExtraIfExists(extra);
									// mApp.basketList.add(new
									// BasketItem(extra));
								}
							}

						}
					}
				}
			}
		}
	}

	private void addArticleIfExists(ArticleBean bean) {
		boolean exists = false;
		for (BasketItem item : mApp.getBasketList()) {
			if (item.getIdArticle().equals(bean.getArticleId()) && item.getIdOption().equals(bean.getOptionId()) && item.getIdExtra().equals("")) {
				item.setCount(Integer.toString(Integer.parseInt(item.getCount()) + 1));
				exists = true;
			}

		}
		if (!exists) {
			mApp.getBasketList().add(new BasketItem(bean));
		}
	}

	private void addExtraIfExists(ExtraBean extra) {

		boolean exists = false;
		for (BasketItem item : mApp.getBasketList()) {
			if (item.getIdArticle().equals(extra.getIdArticle()) && item.getIdOption().equals(extra.getIdOption()) && item.getIdExtra().equals(extra.getIdExtra()) && !item.getIdExtra().equals("")) {
				item.setCount(Integer.toString(Integer.parseInt(item.getCount()) + 1));
				exists = true;
			}

		}
		if (!exists) {
			mApp.getBasketList().add(new BasketItem(extra));
		}
	}

	private void buttonListeners() {
		Button deliveryButton = (Button) findViewById(R.id.btn_order_delivery);
		if (mApp.getSettings() != null && mApp.getSettings().getDeliveryStatus() != null && mApp.getSettings().getDeliveryStatus().equals("Y") && mApp.getBasketList().size() > 0) {
			deliveryButton.setVisibility(View.VISIBLE);
		} else {
			deliveryButton.setVisibility(View.GONE);
		}
		deliveryButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(BasketActivity.this, DeliveryActivity.class);
				startActivityForResult(intent, 10);
			}
		});

		Button pickUpButton = (Button) findViewById(R.id.btn_order_pickup);
		if (mApp.getSettings() != null && mApp.getSettings().getDeliveryStatus() != null && mApp.getSettings().getPickupStatus().equals("Y") && mApp.getBasketList().size() > 0) {
			pickUpButton.setVisibility(View.VISIBLE);
		} else {
			pickUpButton.setVisibility(View.GONE);
		}
		pickUpButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(BasketActivity.this, PickupActivity.class);
				startActivityForResult(intent, 10);
			}
		});
	}

	private void footerMenuListeners() {

		View homeButton = findViewById(R.id.home);
		homeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(100);
				finish();
			}
		});

		View categoriesButton = findViewById(R.id.categories);
		categoriesButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(200);
				finish();
			}
		});

		View basketButton = findViewById(R.id.basket);
		basketButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			}
		});

		View searchButton = findViewById(R.id.search);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setResult(resultCode);
		switch (resultCode) {
		case 100:
			finish();
			break;

		case 200:
			finish();
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_basket, menu);
		return true;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		mApp.getHappie_prefs().edit().putString("BasketList", Common.basketArrayToJson(mApp.getBasketList())).commit();
	}

	@Override
	protected void onDestroy() {
		if (logoDownloader != null) {
			logoDownloader.clearImages();
		}
		if (getArticlesTask != null) {
			getArticlesTask.setRequestCompleteListener(null);
		}
		super.onDestroy();
	}

}
